<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Project } from '../entity'
import * as projectApi from '../api'
import type { Server } from '@renderer/server/entity'
import * as serverApi from '@renderer/server/api'
import { useRouter } from 'vue-router'

// 查询参数
const queryParams = ref({
  page: 1,
  pageSize: 10,
  name: ''
})

// 表格数据
const tableData = ref<Project[]>([])
const total = ref(0)
const loading = ref(false)

// 表格选中项
const selectedRows = ref<Project[]>([])

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<Partial<Project>>({})
const formMode = ref<'add' | 'edit'>('add')

// 服务器列表
const serverList = ref<Server[]>([])

const router = useRouter()

// 加载表格数据
const loadData = async () => {
  try {
    loading.value = true
    const result = await projectApi.getByPage(queryParams.value)
    tableData.value = result.list
    total.value = result.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.value.page = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  queryParams.value = {
    page: 1,
    pageSize: 10,
    name: ''
  }
  loadData()
}

// 分页变化
const handlePageChange = (page: number) => {
  queryParams.value.page = page
  loadData()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  queryParams.value.pageSize = size
  queryParams.value.page = 1
  loadData()
}

// 选择行变化
const handleSelectionChange = (rows: Project[]) => {
  selectedRows.value = rows
}

// 打开新增对话框
const handleAdd = () => {
  formMode.value = 'add'
  dialogTitle.value = '新增项目'
  formData.value = {
    name: '',
    path: '',
    description: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话��
const handleEdit = (row: Project) => {
  formMode.value = 'edit'
  dialogTitle.value = '编辑项目'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 选择项目路径
const handleSelectPath = async () => {
  try {
    const result = await window.dialog.showOpenDialog({
      properties: ['openDirectory']
    })
    if (!result.canceled && result.filePaths.length > 0) {
      formData.value.path = result.filePaths[0]
    }
  } catch (error) {
    console.error('选择路径失败:', error)
    ElMessage.error('选择路径失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!formData.value.name || !formData.value.path) {
      ElMessage.warning('请填写必填项')
      return
    }

    // 检查名称是否存在
    const exists = await projectApi.checkNameExists(
      formData.value.name!,
      formMode.value === 'edit' ? formData.value.id : undefined
    )
    if (exists) {
      ElMessage.warning('项目名称已存在')
      return
    }

    if (formMode.value === 'add') {
      await projectApi.add(formData.value as Omit<Project, 'id' | 'createTime' | 'updateTime'>)
    } else {
      await projectApi.update(formData.value as Project)
    }

    ElMessage.success(`${formMode.value === 'add' ? '新增' : '编辑'}成功`)
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 删除
const handleDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm('确认删除选中的项目吗？', '提示', {
      type: 'warning'
    })
    await projectApi.remove(id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }

  try {
    await ElMessageBox.confirm('确认删除选中的项目吗？', '提示', {
      type: 'warning'
    })
    await Promise.all(selectedRows.value.map(row => projectApi.remove(row.id)))
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 加载服务器列表
const loadServerList = async () => {
  try {
    const result = await serverApi.getByPage({ page: 1, pageSize: 1000 })
    serverList.value = result.list
  } catch (error) {
    console.error('加载服务器列表失败:', error)
    ElMessage.error('加载服务器列表失败')
  }
}

// 添加查看详情方法
const handleViewDetail = (row: Project) => {
  router.push(`/project/${row.id}`)
}

// 时间格式化函数
const formatDateTime = (time: string) => {
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="project-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="项目名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="项目名称" prop="name">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleViewDetail(row)">{{ row.name }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="项目路径" prop="path" show-overflow-tooltip />
      <el-table-column label="描述" prop="description" show-overflow-tooltip />
      <el-table-column label="更新时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="项目名称" required>
          <el-input v-model="formData.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目路径" required>
          <el-input v-model="formData.path" placeholder="请选择项目路径">
            <template #append>
              <el-button @click="handleSelectPath">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.project-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-operations {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.mx-1 {
  margin: 0 4px;
}

.mb-4 {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;

  :deep(.el-pagination) {
    .el-pagination__total {
      margin-right: 16px;
    }

    .el-select .el-input {
      width: 110px;
    }

    button {
      background-color: var(--el-bg-color);

      &:hover {
        color: var(--el-color-primary);
      }
    }

    .el-pager li {
      background-color: var(--el-bg-color);

      &.is-active {
        color: var(--el-color-primary);
        font-weight: bold;
      }
    }
  }
}
</style>

